package com.game.backend.service.impl.user.bot;

import com.game.backend.mapper.BotMapper;
import com.game.backend.model.User;
import com.game.backend.service.impl.utils.UserDetailsImpl;
import com.game.backend.service.user.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AddServiceImpl implements AddService {
    @Autowired
    private BotMapper botMapper;

    @Override
    public Map<String, String> add(String title, String description, String content) {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();

        User user = loginUser.getUser();
        Map<String,String> map = new HashMap<>();
        if(!StringUtils.hasLength(title)){
            map.put("msg","标题不能为空");
            return map;
        }
        if(title.length() > 100){
            map.put("msg","标题的长度不能超过100个字符");
            return map;
        }
        if(!StringUtils.hasLength(description)){
            description = "这个家伙很懒，什么也没写~";
        }
        if(description.length() > 500){
            map.put("msg","介绍的长度不能超过500个字符");
        }
        if(!StringUtils.hasLength(content)){
            map.put("msg","内容不能为空");
            return map;
        }
        if(content.length() > 10000){
            map.put("msg","内容长度不能超过10000个字符");
            return map;
        }

        int res = botMapper.add(user.getId(),title,description,content);
        if(res == 1){
            map.put("msg","success");
        }else{
            map.put("msg","添加数据库失败");
        }
        return map;
    }
}
